package persistence

import (
	"fmt"

	"github.com/beego/beego/v2/client/orm"
	_ "github.com/go-sql-driver/mysql"
)

type PersistenceMysql struct {
	MysqlHost   string
	MysqlPort   int
	MysqlUser   string
	MysqlPasswd string
	MysqlName   string
}

func (pm PersistenceMysql) Init(host string, port int, user, passwd, name string) PersistenceMysql {
	pm.MysqlHost = host
	pm.MysqlPort = port
	pm.MysqlUser = user
	pm.MysqlPasswd = passwd
	pm.MysqlName = name
	orm.RegisterDataBase("default", "mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", user, passwd, host, port, name))

	orm.RegisterModel(new(ArbitragePosition), new(SymbolExchangeInfo))
	orm.RunSyncdb("default", false, true)

	return pm
}

func (pm PersistenceMysql) InsertArbitragePosition(symbol string, spotCount, futureCount float64, spotPrice, futurePrice float64) {
	o := orm.NewOrm()
	position := ArbitragePosition{Symbol: symbol, SpotCount: spotCount, FutureCount: futureCount, SpotPrice: spotPrice, FuturePrice: futurePrice}
	tmpPosition := ArbitragePosition{}
	err := o.QueryTable(tmpPosition.TableName()).Filter("symbol", symbol).One(&tmpPosition)
	if err != nil {
		position.Id = tmpPosition.Id
		_, err = o.Update(&position)
		if err != nil {
			panic(err)
		}
	} else {
		_, err = o.Insert(&position)
		if err != nil {
			panic(err)
		}
	}
}

func (pm PersistenceMysql) QueryArbitragePosition(symbol string) (position ArbitragePosition, err error) {
	o := orm.NewOrm()
	position = ArbitragePosition{}
	err = o.QueryTable(position.TableName()).Filter("symbol", symbol).One(&position)

	return
}
func (pm PersistenceMysql) QueryAllArbitragePosition() (positions []ArbitragePosition, err error) {
	positions = make([]ArbitragePosition, 0)
	o := orm.NewOrm()
	_, err = o.QueryTable((&ArbitragePosition{}).TableName()).All(&positions)

	return
}

func (pm PersistenceMysql) DeleteArbitragePosition(symbol string) error {
	o := orm.NewOrm()
	position := ArbitragePosition{}
	err := o.QueryTable(position.TableName()).Filter("symbol", symbol).One(&position)
	if err != nil {
		return err
	}
	_, err = o.Delete(&position)
	return err
}

func (pm PersistenceMysql) QueryAllSymbolExchangeInfo() (exchangeInfoMap map[string]SymbolExchangeInfo, err error) {
	o := orm.NewOrm()
	exchangeInfoMap = make(map[string]SymbolExchangeInfo)
	var infs []SymbolExchangeInfo
	_, err = o.QueryTable((&SymbolExchangeInfo{}).TableName()).All(&infs)
	if err != nil {
		return
	}
	for _, inf := range infs {
		exchangeInfoMap[inf.Symbol] = inf
	}

	return
}
